import { Toast } from 'antd-mobile';
import { ACTION_TYPES } from 'utils/constant';
import { Post, Get } from 'utils/handler';
import socket from 'utils/socket';

// 提交登录信息
export const postLogin = data => dispatch => {
    const { name, password } = data;
    dispatch({
        type: ACTION_TYPES.LOGIN_REQUEST,
        loading: true,
        isLogin: false,
    });
    return Post('/user/login', {
        name,
        password
    }).then(res => {
        if (res.reasonCode === 200) {
            dispatch({
                type: ACTION_TYPES.LOGIN_SUCCESS,
                isLogin: true,
                loading: false
            })        
            return res.token;
        } else {
            dispatch({
                type: ACTION_TYPES.LOGIN_FAIL,
                loading: false,
                isLogin: false
            })   
            // Toast.fail(res.message || '登录失败');
            return false;    
        }
    }).catch(e => {
        dispatch({
            type: ACTION_TYPES.LOGIN_FAIL,
            loading: false,
            isLogin: false
        })
        // Toast.fail('登录失败');
        return false;
    })
} 

export const getUser = data => dispatch => {
    const token = localStorage.getItem('token');
    dispatch({
        type: ACTION_TYPES.GET_USER_INFO_REQUEST,
        loading: true,
    })
    return Get('/user/get', {
        headers: {
            ['x-access-token']: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.reasonCode === 200) {   
            localStorage.setItem('token', res.token)         
            dispatch({
                type: ACTION_TYPES.GET_USER_INFO_SUCCESS,
                loading: false,
                user: res.user,
                isLogin: true
            })
        } else {
            dispatch({
                type: ACTION_TYPES.GET_USER_INFO_FAIL,
                loading: false,
                isLogin: false
            })
        }
    }).catch(e => {
        dispatch({
            type: ACTION_TYPES.GET_USER_INFO_FAIL,
            loading: false,
            isLogin: false
        })
    })
    
}


// export const login = data => dispatch => {
//     socket.emit('login', data);
//     socket.on('loginSuccess', function(res) {
//         if (res.reasonCode === 200) {
//             dispatch({
//                 type: ACTION_TYPES.LOGIN_SUCCESS,
//                 user: res.data
//             })
//         } else if (res.reasonCode === 404) {
//             dispatch({
//                 type: ACTION_TYPES.LOGIN_FAIL
//             })
//         }
        
//     })
// }